import React ,{ Component }  from 'react'

import {Table as AntTable,message,Icon,Button,TimePicker,DatePicker,Radio,Input } from 'antd'

import moment from 'moment'

import {Link as Linko} from 'react-router-dom'

import api from '../../common/request'


import '../../common/table.css'

import '../../static/brief/step.styl'


import { connect } from 'react-redux'

const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const styles=['neutral','positive','reverse']

class Addtag extends Component{
  constructor(props){
    super(props);
    if(!localStorage.Temporarymaterial){
      localStorage.Temporarymaterial=JSON.stringify([])
    }
    let Hlist=JSON.parse(localStorage.Temporarymaterial)
    let isHas=Hlist.indexOf(this.props.deId)>=0
    this.state={
      active:isHas
    }
  }
  addClick(id){
    this.setState(prevState=>({
      active:!prevState.active
    }))
    let readArr=[]
    if(localStorage.Temporarymaterial){
      let _readArr = localStorage.Temporarymaterial
      readArr=JSON.parse(_readArr)
      if(readArr.indexOf(this.props.deId)===-1){
        readArr.push(this.props.deId)
      }
      localStorage.Temporarymaterial =JSON.stringify(readArr)
    }else{
      readArr.push(this.props.deId)
      let _readArr1 = JSON.stringify(readArr);
      localStorage.Temporarymaterial = _readArr1
    }
    this.props.click()
  }
  render(){
    if(!this.state.active){
      return(
        <span onClick={()=>this.addClick(this.props.deId)}><Icon type="plus"></Icon>添加至简报</span>
      )
    }else{
      return(
        <span><Icon type="plus"></Icon>已加入简报素材</span>
      )
    }

  }
}
@connect(
  state => state.inforesult,
)

export default class Antable extends Component{
  constructor(props){
    super(props);
    this.mountProps(props);
    this.state={
      id:'#',
      tabledata:[],
      startDate:this.startDate(),
      endDate:this.endDate(),
      startTime:"00:00:00",
      endTime:this.nowTime(),
      sortType:'asc',
      pageSize:1,
      pageNo:10,
      strTime:'',
      endstrTime:'',
      deleIds:'',
      matdeleIds:[],
      active:false,
      total:0,
      InpValue:'',
      sortEType:'desc'

    }
    //改变日期
    this.onChange=this.onChange.bind(this)
    //改变时间
    this.onChangeTime=this.onChangeTime.bind(this)
    this.handleChange=this.handleChange.bind(this)
    this.handleSure=this.handleSure.bind(this)
    this.onChangendTime=this.onChangendTime.bind(this)
    this.onChangedate=this.onChangedate.bind(this)
    //降序、升序
    this.chengSorttype=this.chengSorttype.bind(this)
    //删除
    this.deleDate=this.deleDate.bind(this)
    //分页
    this.handChangeSize=this.handChangeSize.bind(this)
    //搜索
    this.handleSearch=this.handleSearch.bind(this)
    //简报添加
    this.addMaterial=this.addMaterial.bind(this)
    //编辑简报素材升序
    this.handAsc=this.handAsc.bind(this)

  }
  fnPensity=(value)=>{
    let typrht='';
    switch(parseInt(value)){
      case -1:
        typrht='全部';
        break;
      case 0:
        typrht='中性';
        break;
      case 1:
        typrht='正面';
        break;
      case 2:
        typrht='负面';
        break;
      default:
        typrht=value
    }
    return typrht;
  };


  componentDidMount(){
    this._renderdata()
  }
  //初始化数据
  async _renderdata(){
  await this.setState({
      strTime:this.state.startDate+' '+this.state.startTime,
      endstrTime:this.state.endDate+' '+this.state.endTime
    })
    if(this.props.typeLi==="biref"){
      await api.brieData(this.state.strTime,this.state.endstrTime,this.state.pageSize,this.state.pageNo,this.state.sortType).then(res=>{
        if(res.data.success){
          this.setState({
            tabledata:res.data.data,
            total:res.data.totals
          })
        }
      })
    }else if(this.props.typeLi==="infolist"){
      await api.oprender(this.state.strTime,this.state.endstrTime,this.state.pageSize,this.state.pageNo,this.state.sortType).then(res=>{
        if(res.data.success){
          this.setState({
            tabledata:res.data.data,
            total:res.data.totals
          })
        }
      })
    }
    else if(this.props.typeLi==="allsearch"){
      await api.searhome(this.state.InpValue,this.state.pageSize,this.state.pageNo,this.state.sortType).then(res=>{
        if(res.data.success){
          this.setState({
            tabledata:res.data.data,
            total:res.data.totals
          })
        }
      })
    }
    else if(this.props.typeLi==="editor"){
      let Len=0
      if(localStorage.Temporarymaterial){
        Len=JSON.parse(localStorage.Temporarymaterial)
      }
      if(Len.length>=0){
        let ids=Len.join(',')
        await api.renderEditor(ids,this.state.sortEType).then(res=>{
          if(res.data.success){
            this.setState({
              tabledata:res.data.data,
              total:res.data.total
            })
          }else{
            this.setState({
              tabledata:res.data.data,
              total:res.data.total
            })
          }
        })
      }else{
        return false
      }


    }

  }
    //input 框
    onchangeInput(e){
      this.setState({
        InpValue:e.target.value
      })
    }
    //搜索确定
    handleSearch(){
      this._renderdata()
    }
    //确定
  handleSure(){
    this._renderdata()
  }
  //默认开始时间
  startDate(){
    return moment().format('YYYY-MM-DD')
  }
  //默认结束时间
  endDate(){
    return moment().format('YYYY-MM-DD')
  }
  //默认时间
  nowTime(){
    return moment().format('HH:mm:ss')
  }
  componentWillReceiveProps(props) {
    this.mountProps(props);
  }

  changeId(Id){
      this.setState({
        id:'#'+Id
      })
  }



  //降序、升序
  async chengSorttype(e){
    await this.setState({
      sortType:e.target.value
    })
    await this._renderdata()
  }
  //删除
  deleDate(){
    if(this.props.typeLi==='biref'){
      api.deleData(this.state.matdeleIds).then(res=>{
        if(res.data.success){
          message.success('删除成功')
          this.setState({
            matdeleIds:'',
          })
          this._renderdata()
        }else{
          message.error(res.data.message)
        }
      })
    }else if(this.props.typeLi==='infolist'){
      api.deleInfoData(this.state.deleIds).then(res=>{
        if(res.data.success){
          message.success('删除成功')
          this.setState({
            deleIds:'',
          })
          this._renderdata()
        }else{
          message.error(res.data.message)
        }
      })
    }
  }

  //素材库页面

  //素材库移除
  handmove(id){
    let ids=JSON.parse(localStorage.Temporarymaterial)
    let oIndex=ids.indexOf(id)
    ids.splice(oIndex,1)
    localStorage.Temporarymaterial=JSON.stringify(ids)
    this.props.hanClick(ids.length)
    this._renderdata()
  }

    //清空素材库
    handMovaeAll(){
      localStorage.Temporarymaterial=JSON.stringify([])
      let ids=JSON.parse(localStorage.Temporarymaterial)
      this.props.hanClick(ids.length)
      this._renderdata()
    }
  //降序
    async handAsc(){
      await this.setState({
        sortEType:'asc'
      })
      await this._renderdata()
    }
    //选择删除
    handSedele(){
      if(this.state.deleIds.length<=0){
        return message.error('请选择要删除的素材')
      }
      let arr=this.state.deleIds.split(',')
      let ids=JSON.parse(localStorage.Temporarymaterial)
      arr.map((d,index)=>{
        if(ids.indexOf(d)!==-1){
          let oIndex=ids.indexOf(d)
          ids.splice(oIndex,1)
        }
        return ids
      })
      localStorage.Temporarymaterial=JSON.stringify(ids)
      this.props.hanClick(ids.length)
      this._renderdata()
    }
  //链接跳转id设置
  detailset(id,key){
    if(!localStorage.id){
      localStorage.id=id;
      localStorage.titleContentPrint=key;
    }else{
      localStorage.id=id;
      localStorage.titleContentPrint=key
    }


  }
//高亮
createMarkup(page) {
  let res;
  if(page){
    //res=page
    res = page.replace(/<br \/>/g,'').replace(/{{{/g,"<span class='light' style='color:red'>").replace(/}}}/g,"</span>")
  }else{
    res=page
  }
  return {__html: res};
  };
//分页
async handChangeSize(current){
  await this.setState({
    pageSize:current
  })
  await this._renderdata()
}
  mountProps(props) {
    const {
      header,
      action,
      headerWidth,
      // currentPage,
      data,
      } = props;
    /*this.state = {
      currentPage,

    }*/
    this.makeColumns(header, action, headerWidth, data);
  }
  makeColumns(headers, action, headerWidth, data){
    this.columns = [{
      dataIndex: 'name',
      key: 'name',
      render:(text,record)=>(
        <div className="srcpos">
          <img className="src1" src={'image/'+record.domain+'.png'}  alt=""></img>
          <img className="src2" src={'image/defult.png'}  alt=""></img>
        </div>
      ),
    },{
      dataIndex: 'address',
      key: 'address',
      render:(text,record)=>(
        <div className="fiter-info" id={record.id}>
          <div className="title-p">
            <Linko to={this.props.typeLi!=="allsearch"?'/detail?t='+Date.parse(new Date())+'&type='+(record.favoriteId?1:0):record.url} target='_blank'>
              <div  onClick={()=>this.detailset(record.favoriteId?record.favoriteId:record.id,record.titleContentPrint?record.titleContentPrint:'')} className='titl' dangerouslySetInnerHTML={this.createMarkup(record.title)}></div>
              </Linko>
              <div className={"type " + styles[record.positiveOrNegative]}>{record.positiveOrNegative?this.fnPensity(record.positiveOrNegative):this.fnPensity(record.positiveOrNegative)}</div>
              <span>{record.doc_count}</span>
              <div className="time">{record.poTime?record.poTime.toString().indexOf('-',2)>=0?record.poTime:moment(Math.abs(parseInt(record.poTime,0))).format('YYYY-MM-DD HH:mm:ss'):record.potime}</div>
          </div>
          <div className='info show' dangerouslySetInnerHTML={this.createMarkup(record.content)}></div>
          <div className="footer">
            <div className="source">
              <span>来源：</span>
              <span>{record.webSite}</span>
            </div>
            <div className={this.props.typeLi==='editor'?"shide":''}>
              <Addtag click={this.addMaterial} deId={record.id}></Addtag>
            </div>
            <div className={this.props.typeLi==='editor'?"isShow":'shide'}>
              <span onClick={()=>this.handmove(record.id)}><Icon type="delete" />移除简报素材</span>
            </div>
          </div>
        </div>
      )
    }];
      }
  onPageChangeHandler = (currentPage) => {
    this.props.onChange(currentPage)

  }
  handleChange(value){
    this.props.changeSize(Number(value))
  }

  //改变初始日期
  onChange(date,dateString){
    this.setState({
      startDate:dateString
    })
  }
  //改变初始时间
  onChangeTime(time,timeString){
    this.setState({
      startTime:timeString+":00",
    })
  }

  //改变结束日期
  onChangedate(date,dateString){
    this.setState({
      endDate:dateString
    })
  }
  //改变结束时间
  onChangendTime(time,timeString){
    this.setState({
      endTime:timeString+":00"
    })

  }
  //单选、全选
  rowSelection={
    onChange: (selectedRowKeys, selectedRows) => {
      let arr=[]
      selectedRows.map((item,index)=>{
        if(('favoriteId' in item)){
          arr.push(item.favoriteId)
        }
      })
      let str=selectedRowKeys.join(',')
      let str1=arr.join(',')
      this.setState({
        deleIds:str,
        matdeleIds:str1
      })
    }
  }
  //添加至简报
  addMaterial(){
    let len=JSON.parse(localStorage.Temporarymaterial).length
    this.props.hanClick(len)
  }
  render(){
    return(
      <div>
        <div className={this.props.typeLi==="allsearch"?"search ":'shide'} >
          <Input placeholder="请输入搜索内容" onChange={(e)=>this.onchangeInput(e)} value={this.state.InpValue}/>
          <Button type='primary' onClick={this.handleSearch}>搜索</Button>
        </div>
        <div className={'t'}>
          <div className={(this.props.typeLi==="allsearch" || this.props.typeLi==='editor' )?"li shide":'li'}>
            <label>检测时间：</label>
            <span><DatePicker defaultValue={moment(this.startDate())} onChange={this.onChange}/></span>
            <span><TimePicker format="HH:mm" defaultValue={moment('00:00','HH:mm')} onChange={this.onChangeTime}></TimePicker></span>
            <span className="interval">to</span>
            <span><DatePicker  defaultValue={moment(this.endDate())} onChange={this.onChangedate}/></span>
            <span><TimePicker format="HH:mm" defaultValue={moment(this.nowTime(),'HH:mm')}  onChange={this.onChangendTime}></TimePicker></span>
            <Button type="primary" onClick={this.handleSure}>确定</Button>
            <label>时间排序：</label>
            <RadioGroup  defaultValue="asc" onChange={this.chengSorttype}>
              <RadioButton value="asc">时间升序</RadioButton>
              <RadioButton value="desc">时间降序</RadioButton>
            </RadioGroup>
            <Button onClick={this.deleDate}>删除</Button>
          </div>
          <div className={this.props.typeLi==='editor'?'li':'shide'}>
            <Button onClick={()=>this.handMovaeAll()}>清空素材库</Button>
            <Button onClick={()=>this.handAsc()}>时间升序</Button>
            <Button onClick={()=>this.handSedele()}>删除</Button>
          </div>
        </div>

        <AntTable
            rowKey="id"
            bordered={true}
            rowSelection={this.rowSelection}
            columns={this.columns}
            dataSource={this.state.tabledata}
            pagination={{
              total: this.state.total,
              pageSize:this.state.pageNo,
              defaultPageSize:this.state.pageSize,
              onChange:this.handChangeSize
            }}
            loading={this.state.loading} ></AntTable>
      </div>
    )
  }
}